package org.chen.scene.scheduler;

import lombok.extern.slf4j.Slf4j;
import org.chen.common.scene.entity.Attraction;
import org.chen.scene.service.AttractionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;


@Slf4j
@Component
public class AttractionDetailsScheduler {
    @Autowired
    private AttractionService attractionService;

    // 每3小时检查一次未获取详情的商品
    @Scheduled(cron = "0 0 0/3 * * *")
    public void fetchProductDetails() {
        log.info("开始获取景点详情");

        List<Attraction> unfetchedProducts = attractionService.getUnfetchedDetailProducts();

        if (unfetchedProducts.isEmpty()) {
            log.info("没有需要获取详情的景点");
            return;
        }

        log.info("发现{}个需要获取详情的景点", unfetchedProducts.size());

        for (Attraction attraction : unfetchedProducts) {
            Map<String, String> details = attractionService.scrapeWithTimeout(attraction.getDetailUrl());

            if (details != null && !details.isEmpty()) {
                // 更新数据库
                attractionService.updateAttractionDetails(attraction.getPoiId(), details);

                log.debug("成功抓取景点 {} 详情", attraction.getPoiId());
            }
        }

        log.info("景点详情获取任务已提交");
    }
}
